package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 根据所给定的日期区间获得营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //进行日期字符串的返回
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //每天营业额的返回
        List<Double> turnoverList=new ArrayList<>();
        for (LocalDate date : dateList) {
            //localdatetime转化成localdate
            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);

            //select sum(amount) from orders where order_time>? and order_time<? and status=5
            Map map=new HashMap<>();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover= orderMapper.getByMap(map);
            turnover= turnover==null ? 0.0:turnover;
            turnoverList.add(turnover);
        }
        TurnoverReportVO turnoverReportVO = TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();

        return turnoverReportVO;
    }

    /**
     *
     * 根据给定的日期区间获得用户数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //进行日期处理
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //进行用户处理
        List<Integer> newUserList=new ArrayList<>();
        List<Integer> totalUserList=new ArrayList<>();
        for (LocalDate date : dateList) {
            //localdatetime转化成localdate
            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);

            Map map=new HashMap<>();
            map.put("endTime",endTime);
            Integer toatalUser= userMapper.getByMap(map);
            totalUserList.add(toatalUser);
            map.put("beginTime",beginTime);
            Integer newUser=userMapper.getByMap(map);
            newUserList.add(newUser);
        }
        UserReportVO userReportVO=UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
        return userReportVO;
    }


    /**
     * 根据所给的日期区间订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //对于日期处理
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //订单数列表处理
        List<Integer> orderCountList=new ArrayList<>();//订单数列表
        List<Integer> vaildOrderCountList=new ArrayList<>();//有效订单数列表
        for (LocalDate date : dateList) {

            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);
            //select count(*) from order where order_time>? and order_time<? (and status=5)
            Map map=new HashMap<>();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            Integer orderCount= orderMapper.getCountByMap(map);//订单数
            orderCountList.add(orderCount);
            map.put("status", Orders.COMPLETED);
            Integer vaildOrderCount=orderMapper.getCountByMap(map);//有效订单数
            vaildOrderCountList.add(vaildOrderCount);
        }
//        Integer totalOrderCount=0;
//        for (Integer i : orderCountList) {
//            toatlOrderCount+=i;
//        }
//        Integer vaildOrderCount=0;
//        for (Integer i : vaildOrderCountList) {
//            vaildOrderCount+=i;
//        }
        //用stream流得到集合之和
        Integer totalOrderCount=orderCountList.stream().reduce(Integer::sum).get();
        Integer vaildOrderCount=vaildOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate=0.0;
        if(totalOrderCount!=0){
            orderCompletionRate=(double)vaildOrderCount/(double)totalOrderCount;
        }
        OrderReportVO orderReportVO = OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(vaildOrderCountList, ","))
                .orderCompletionRate(orderCompletionRate)
                .validOrderCount(vaildOrderCount)
                .totalOrderCount(totalOrderCount)
                .build();
        return orderReportVO;
    }

    /**
     * top10菜品统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {

        //时间转化，转化成具体时间
        LocalDateTime beginTime=LocalDateTime.of(begin, LocalTime.MIN);//给定范围时间最开始的时候
        LocalDateTime endTime=LocalDateTime.of(end, LocalTime.MAX);//给定范围时间最晚的时候
        //商品名称列表
        List<String> nameList=orderDetailMapper.getNameByTime(beginTime,endTime,Orders.COMPLETED);
        List<Integer> numberList=orderDetailMapper.getNumberByTime(beginTime,endTime,Orders.COMPLETED);
        //select DISTINCT name from order_detail left join orders where ordertime<? and ordertime>?封装给集合
        //select count(name) from order_detail left join orders where ordertime<? and ordertime>? group by name

        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
        return salesTop10ReportVO;
    }


    /**
     * 近三十天数据导出
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        //获得概览数据
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        LocalDateTime beginTime=LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(endDate, LocalTime.MAX);

        BusinessDataVO businessDataVO = workspaceService.getBusinessData(beginTime, endTime);
        try {
            //填入Excel
            InputStream in=this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
            //基于模版创建Excel
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheetAt(0);
            CellStyle style = excel.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            sheet.getRow(1).getCell(1).setCellStyle(style);
            sheet.getRow(1).getCell(1).setCellValue("时间："+beginDate+"至"+endDate);
            //概览数据填入
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            row=sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //详细数据填入
            for (int i = 0; i < 30; i++) {
                LocalDate date=beginDate.plusDays(i);
                LocalDateTime begin=LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime end=LocalDateTime.of(date, LocalTime.MAX);
                BusinessDataVO vo = workspaceService.getBusinessData(begin, end);
                row = sheet.getRow(i+7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(vo.getTurnover());
                row.getCell(3).setCellValue(vo.getValidOrderCount());
                row.getCell(4).setCellValue(vo.getOrderCompletionRate());
                row.getCell(5).setCellValue(vo.getUnitPrice());
                row.getCell(6).setCellValue(vo.getNewUsers());
            }
            //文件下载
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
